const computedBehavior = require('miniprogram-computed')
import api from "../../../../common/api"
import constant from '../../../../common/constant';
import util from "../../../../utils/util";
import {
  gioInviterLog
} from "../../../../common/gioHandler";
import * as user from '../../../../models/user'
var app = getApp();

let shareInfo = {}
Page({
  behaviors: [computedBehavior],

  /**
   * 页面的初始数据
   */
  data: {
    height: 0,
    top: 0,
    current: 0,
    num: 0,
    testlist: [],
    rule: false, //规则页面的弹窗
    actEntreVar: '',
    defaultTabSelect: "PENDING",
    tabSelect: "PENDING",
    tabList: [{
        id: "PENDING",
        label: "邀请记录"
      },
      {
        id: "COMPLETED",
        label: "已获得奖励"
      }
    ],
    scanVisible: false, //面对面扫码
    postersVisible: false, //盆友圈海报
    isShowBatch: true, //是否关注过公众号
    list_item: [], //邀请记录
    receiveList_item: {}, //以获得奖励=====天数和价钱
    list_YHDJL: [], //以获得奖励  ===列表
    btnFloat: false, //显示btn1或者btn2
    paintPallette: {},//朋友圈海报
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    wx.showShareMenu({
      withShareTicket: true,
    });
    this.data.actEntreVar = options.actEntre || constant.null;

    app.globalData.loginPromise.then(() => {
      gioInviterLog(constant.viewInvite, this.data.actEntreVar)
      this.getNavHeight();
      this.topBanner()
      this.isBatch()
      this.getInviteRecode()

      api.getAppletSharingInfo({
        refCode: 'AppletSharing'
      }, res => {
        if (res && res.data && res.data.isSuccess) {
          let content = res.data.content
          shareInfo = {
            title: content.refDetailName,
            imageUrl: content.list[0],
          }
        }
      })
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () { },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function (e) {},

  /**
   * 页面相关事件处理函数--监听用户鼠标滚动
   */
  onPageScroll: function (e) {
    let that = this;
    let query = wx.createSelectorQuery()
    query.select('.share-btn').boundingClientRect((rect) => {
      let top = rect.top;
      let height = rect.height;
      if (top < -height) {
        that.setData({
          btnFloat: true
        })
      } else {
        that.setData({
          btnFloat: false
        })
      }
    }).exec()
  },
  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {},

  // tab改变获取数据
  onTabChange(e) {
    const {
      tabSelect
    } = this.data;
    let target = e.detail;
    if (tabSelect === target) return;
    if (target === 'PENDING') {
      this.getInviteRecode()
    }
    if (target === 'COMPLETED') {
      this.queryUserFissionRewardList()
    }
    this.setData({
      tabSelect: target,
    });

  },

  // 顶部轮播
  topBanner() {
    api.dyNamicState({
      page: 1,
      pageSize: 100,
    }, res => {
      let rows = res.data.content.rows;
      rows.map(v => {
        let remark = Number(v.remark);
        v.remark = remark.toFixed(2)
      })
      this.setData({
        testlist: rows
      })
    })
  },

  // 面对面扫码
  handleToggleScan() {
    this.setData({
      scanVisible: false
    })
  },
  handleShowScan() {
    this.setData({
      scanVisible: true
    })

    gioInviterLog(constant.clickscancode, this.data.actEntreVar)
  },
  // 盆友圈海报
  handleShowFriend() {
    let t = this
    wx.showLoading({
      mask: true,
      title: '海报制作中...',
    })
    t.posterInfo().then((res) => {
      t.setData({
        paintPallette: {
          width: '750rpx',
          height: '1354rpx',
          background: res.bgImg,
          views: [{
              type: 'rect',
              css: {
                top: '1104rpx',
                left: '30rpx',
                width: '690rpx',
                height: '200rpx',
                color: '#fff',
                borderRadius: '10rpx',
              }
            }, {
              type: 'image',
              url: res.userAvatar,
              css: {
                top: '1144rpx',
                left: '70rpx',
                borderRadius: '10rpx',
                width: '120rpx',
                height: '120rpx',
              }
            }, {
              type: 'text',
              text: res.userName,
              css: {
                top: "1144rpx",
                left: '230rpx',
                width: '230rpx',
                fontSize: '36rpx',
                color: '#000',
                fontWeight: 'bold',
                maxLines: '1'
              }
            }, {
              type: 'text',
              text: res.text1,
              css: {
                top: "1200rpx",
                left: '230rpx',
                fontSize: '24rpx',
                color: '#2c2c2c',
              }
            }, {
              type: 'text',
              text: res.text2,
              css: {
                top: "1244rpx",
                left: '230rpx',
                fontSize: '24rpx',
                color: '#ff4747',
              }
            },
            {
              type: 'image',
              url: res.scanUrl,
              css: {
                top: '1134rpx',
                left: '548rpx',
                borderRadius: '140rpx',
                width: '140rpx',
                height: '140rpx',
              }
            },

          ],
        }
      })
    })
    gioInviterLog(constant.clickposters, this.data.actEntreVar)
  },
  onDrawSuccess(e) {
    wx.hideLoading()
    let img = e.detail.path
    let that = this
    if (img && typeof img === 'string') {
      wx.saveImageToPhotosAlbum({
        filePath: img,
        success() {
          that.setData({
            postersVisible: true
          })
        },
        fail: () => {
          wx.getSetting({
            success: (res) => {
              if (!res.authSetting['scope.writePhotosAlbum']) {
                wx.showModal({
                  title: '提示',
                  content: '图片保存失败，请授权相册后重试',
                  success: (res) => {
                    if (res.confirm) {
                      wx.openSetting()
                    }
                  }
                })
              }
            }
          })
        }
      });
    } else {
      wx.showToast({
        title: '海报制作失败，请稍后再试！',
        icon: 'none',
      })
    }
  },
  posterInfo() { // 整理海报的数据
    return new Promise((resolve, reject)=>{
      getApp().globalData.loginPromise.then((content) => {
        let loginUserInfo = getApp().globalData.loginUserInfo;
        let settingInfo = wx.getStorageSync('settingInfo');
        let params = {
          activityCode: 'MEMBERFISSION',
          fromUserId: content.sessionUser.id,
          antreVar: constant.friendsposter
        }
        api.qrcodeLongToShort(JSON.stringify(params), {}, res => {
          let smallCode = res.data.content;
          let QrCode = util.domain + "miniCode/getWXACodeUnlimit?page=" + encodeURI("pages/index/index") + "&scene=" + smallCode + "&miniName=jjrjs"
          let p = {
            scanUrl: QrCode,
            userAvatar: settingInfo.imgArray ? settingInfo.imgArray : loginUserInfo.data.content.sessionUser.avatar,
            userName: settingInfo.name ? settingInfo.name : loginUserInfo.data.content.sessionUser.realName,
            bgImg: '../../images/posterKv.png',
            text1: '邀请您限时免费使用',
            text2: '扫码立即体验'
          }
          resolve(p)
        })
      })
    }) 
  },

  handIKnow() {
    this.setData({
      postersVisible: false
    })
  },
  // 立即关注
  LJGZ() {
    return new Promise((resolve, reject) => {
      user.getOfficialAccount(true).then(res => {
          if (res === '1') {
            resolve()
          } else {
            let url = 'https://mp.weixin.qq.com/s/AsUf1prwyD8cxQMx07UNhw'
            wx.navigateTo({
              url: `/pages/webView/webView?webViewUrl=${url}`
            })
            reject()
          }
        })
        .catch(() => {
          wx.showToast({
            icon: 'none',
            title: '网络错误，请稍后再试~',
          })
        })
    })
  },

  // 检查是否已关注公众号
  isBatch() {
    return new Promise((resolve, reject) => {
      api.isBatch({}, (res) => {
        if (res && res.data) {
          this.setData({
            isShowBatch: res.data.content
          })
          resolve();
        } else {
          reject()
        }
      });
    });
  },

  // 邀请记录
  getInviteRecode() {
    this.selectComponent("#com-scroll-content1").fetchHouse(1, ({
      page
    }) => {
      return new Promise((resolve, reject) => {
        this.setData({
          list_item: []
        });
        api.getInviteRecode({
          page,
          pageSize: 10,
          status: 'ALL'
        }, ({
          data
        }) => {
          data.handleData = (rows) => {
            let tmpRow = []
            for (let i in rows) {
              let tmpRowItem = {}
              tmpRowItem.avatar = rows[i].wxHeadImg
              tmpRowItem.nickname = rows[i].nickName
              tmpRowItem.state = rows[i].state //pending进行中 fail失效 success成功
              tmpRowItem.data = rows[i].info
              if (!rows[i].newUser) {
                tmpRowItem.data = [{
                  type: rows[i].state,
                  time: rows[i].pullNewTime,
                  text: '该用户是老用户，邀请无效'
                }]
              }
              tmpRow.push(tmpRowItem)
            }
            this.setData({
              list_item: this.data.list_item.concat(tmpRow),
            });
          };
          resolve(data);
        }, reject);
      });
    });
  },
  //以获得奖励
  queryUserFissionRewardList() {
    this.setData({
      list_YHDJL: []
    });
    this.selectComponent("#com-scroll-content2").fetchHouse(1, ({
      page
    }) => {
      return new Promise((resolve, reject) => {
        api.queryUserFissionRewardList({
          page,
          pageSize: 10
        }, ({
          data
        }) => {
          let dayAndMoney = {}
          dayAndMoney.vipNum = data.content.allDays || '0'
          dayAndMoney.totalMoney = data.content.allMoney || '0.00'
          this.setData({
            receiveList_item: dayAndMoney
          })
          data.content = data.content.pagedGridResult
          data.handleData = (rows) => {
            this.setData({
              list_YHDJL: this.data.list_YHDJL.concat(rows),
            });
          };
          resolve(data);
        }, reject);
      });
    })
  },
  // 设置导航栏的高度he自定义返回按钮
  getNavHeight() {
    this.setData({
      height: app.globalData.navHeight,
      top: app.globalData.navTop,
    })
  },
  back() {
    if (getCurrentPages().length == 1) {
      wx.reLaunch({
        url: '/pages/index/index'
      })
    } else {
      wx.navigateBack({
        delta: 1,
      })
    }
  },
  // 活动规则
  onpenRule() {
    this.setData({
      rule: true
    })

    gioInviterLog(constant.Click_Rules, this.data.actEntreVar)
  },

  closeRule() {
    this.setData({
      rule: false
    })
  },
  //跳到奖励明细页面
  goToJLMX() {
    let that = this
    wx.gio('track', constant.Click_Reward_Detail, {
      [constant.ActEntre_Aar]: that.data.actEntreVar
    })
    wx.navigateTo({
      url: '/pages/mine/rewardSub/rewardSub?gotoActiveList=activePage',
    })
  },

  getInform() {
    wx.requestSubscribeMessage({
      tmplIds: ["q7f7c3jyFSlAz_1omXdtMIwnu4v4Qy16PAhVbTyIfBs"],
      success(res) {
        for (var key in res) {
          if (key != "errMsg") {
            if (res[key] == "reject") {
              return;
            }
          }
        }
      },
      fail(res) {},
    });
  },
  toGetInform() {
    let that = this;
    setTimeout(() => {
      that.getInform()
    }, 1000)
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    let sessionUser = getApp().globalData.sessionUser;
    let agentId = sessionUser.id;
    gioInviterLog(constant.Click_Share, this.data.actEntreVar)
    return {
      title: shareInfo.title || '兄弟，推房获客黑科技推荐给你！效率高开单多！',
      imageUrl: shareInfo.imageUrl || getApp().globalData.defaultShareImgUrl,
      path: `/pages/index/index?activityCode=MEMBERFISSION&fromUserId=${agentId}&antreVar=${constant.clickcard}`,
    }
  },
})